<template>
  <el-dialog :title="title || '选择用户'" :visible.sync="show" append-to-body :close-on-click-modal="false" width="1000px" @closed="closed">
    <el-form ref="queryForm" :model="queryParams" size="mini" inline :class="{ disabled: disableAction }" style="margin-top: -20px" @submit.native.prevent>
      <el-form-item prop="nickName">
        <el-input v-model.trim="queryParams.nickName" placeholder="请输入名称" clearable @clear="handleQuery" @keyup.enter.native="handleQuery" style="width: 200px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table ref="table" v-loading="listLoading" :data="filteredList" size="small" height="calc(88vh - 200px)" :row-style="{ cursor: 'pointer' }" @row-click="rowClick" @selection-change="onSelect">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="名称" prop="nickName" show-overflow-tooltip />
      <el-table-column label="账户" prop="userName" show-overflow-tooltip />
      <el-table-column label="角色" align="center" show-overflow-tooltip>
        <span slot-scope="{ row }">{{ row.roleIds | roleFilter(role2Name) }}</span>
      </el-table-column>
      <el-table-column label="备注" prop="remark" show-overflow-tooltip />
    </el-table>

    <div slot="footer">
      <span style="font-size: 13px; color: #606266; margin-right: 20px" v-if="showTip">{{ showTip }}</span>
      <el-button type="primary" :disabled="disableAction || !selected.length" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="disableAction" @click="show = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
// 选择选择用户
import { debounce, isLikeOrEqual } from '@/utils'
import { roleList } from '@/api/common'
import { userList } from '@/api/qualityManage/buildingPerson'
export default {
  filters: {
    roleFilter(val, role2Name = {}) {
      const str = val || ''
      return str
        .split(',')
        .map(i => role2Name[i])
        .filter(i => i)
        .join('，')
    }
  },
  props: {
    title: { type: String, default: '' },
    limit: { type: Number, default: undefined }
  },
  data() {
    return {
      show: false,
      listLoading: false,
      list: [],
      filteredList: [],
      queryParams: {
        projectId: '',
        nickName: ''
      },
      roleList: [],
      selected: []
    }
  },
  computed: {
    disableAction() {
      return this.listLoading
    },
    role2Name() {
      return this.roleList.reduce((o, i) => !void (o[i.fid] = i.roleName) && o, {})
    },
    selectedLen() {
      return this.selected.length
    },
    showTip() {
      const { limit } = this
      const len = this.selectedLen
      if (limit) return len ? `已选 ${len} / ${limit} 项` : `最多选择 ${limit} 项`
      return len ? `已选 ${len} 项` : ''
    }
  },
  created() {
    this.btnSubmit = debounce(this.onSubmit, 1e3, true)
  },
  methods: {
    closed() {
      this.listLoading = false
      this.list = []
      this.filteredList = []
      this.queryParams.projectId = ''
      this.resetForm('queryForm')
    },
    open({ projectId }) {
      if (!projectId) return this.$message.error('参数错误：项目ID不能为空')
      this.show = true
      this.queryParams.projectId = projectId
      if (!this.roleList.length) this.getRoleList()
      this.getList()
    },
    async getRoleList() {
      const res = await roleList().catch(() => false)
      if (res === false) return (this.roleList = [])
      this.roleList = res.data || []
    },
    async getList() {
      const opt = { projectId: this.queryParams.projectId }
      this.listLoading = true
      const res = await userList(opt).catch(() => false)
      this.listLoading = false
      if (res === false) return (this.list = [])

      const data = res.data || []
      data.map(i => {
        // 字段改驼峰
        i.nickName = i.nick_name
        i.userName = i.user_name
        i.userId = i.user_id
        i.roleIds = i.rolefids
      })
      this.list = data
      this.handleQuery()
    },
    handleQuery() {
      // 本地搜索
      const { nickName } = this.queryParams
      const opts = { like: { nickName } }
      this.filteredList = this.list.filter(i => isLikeOrEqual(i, opts))
    },
    resetQuery() {
      // 部分字段重置
      this.queryParams.nickName = ''
      this.getList()
    },
    rowClick(row) {
      this.$refs.table.toggleRowSelection(row)
    },
    onSelect(val) {
      this.selected = val
    },
    onSubmit() {
      const { limit } = this
      if (limit && this.selectedLen > limit) return this.msgInfo(`最多选择 ${limit} 项`)

      this.$emit('selected', JSON.parse(JSON.stringify(this.selected)))
      this.show = false
    }
  }
}
</script>
